package com.lai.note.fragment;

import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.lai.note.R;
import com.lai.note.activity.PersonDetailsActivity;
import com.lai.note.activity.RecordsNoteActivity;
import com.lai.note.activity.RecordsWenanActivity;
import com.lai.note.dto.ResponseResult;
import com.lai.note.model.User;
import com.lai.note.service.UserBaseService;
import com.lai.note.util.GsonUtil;
import com.lai.note.util.PhotoUtil;
import com.lai.note.util.RetrofitRequest;
import com.lai.note.util.ToastUtil;
import com.lai.note.util.TokenUtil;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static android.app.Activity.RESULT_OK;
import static androidx.constraintlayout.widget.Constraints.TAG;

public class PersonFragment extends Fragment {
    public PersonFragment() {
        super(R.layout.fragment_person);
    }

    //个人信息控件
    private ImageView iv_userIcon;
    private EditText et_username;
    private TextView tv_update_icon;
    private RelativeLayout relativeLayout_details;
    private RelativeLayout relativeLayout_wenans;
    private RelativeLayout relativeLayout_notes;

    private File tempFile;
    private String filePath;

    private User user = null;

    //retrofit
    private Retrofit retrofit;
    private UserBaseService userBaseService = null;

    private static final int REQUEST_CODE = 8088;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews();
        initUserInfo();


        relativeLayout_details.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("跳转到用户详细资料界面");
                Intent intent = new Intent(getContext(), PersonDetailsActivity.class);
                startActivity(intent);
            }
        });

        relativeLayout_wenans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("跳转到我的文案界面");
                Intent intent = new Intent(getContext(), RecordsWenanActivity.class);
                startActivity(intent);
            }
        });
        relativeLayout_notes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("跳转到我的笔记界面");
                Intent intent = new Intent(getContext(), RecordsNoteActivity.class);
                startActivity(intent);
            }
        });

//        //测试七牛云
//        iv_userIcon.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //使用Intent触发选择Action
//                Intent intent = new Intent(Intent.ACTION_PICK, null);
//                //打开系统提供的图片选择界面
//                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                //传参以在返回本界面时触发加载图片的功能
//                startActivityForResult(intent, 0x1);
//                tv_update_icon.setText("作为头像");
//            }
//        });
//        tv_update_icon.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                uploadImg2QiNiu();
//            }
//        });
    }

    //控件初始化
    private void initViews() {
        iv_userIcon = getView().findViewById(R.id.iv_avatar);
        et_username = getView().findViewById(R.id.et_username);
        tv_update_icon = getView().findViewById(R.id.tv_update_icon);
        relativeLayout_details = getView().findViewById(R.id.re_details);
        relativeLayout_wenans = getView().findViewById(R.id.re_records_wenan);
        relativeLayout_notes = getView().findViewById(R.id.re_records_note);
    }


    private void initUserInfo() {
        retrofit = RetrofitRequest.getInstance(getContext());
        userBaseService = retrofit.create(UserBaseService.class);
        Call<ResponseResult> call = userBaseService.getUserInfo();
        call.enqueue(new Callback<ResponseResult>() {
            @Override
            public void onResponse(Call<ResponseResult> call, Response<ResponseResult> response) {
                ResponseResult res = response.body();
                if (res != null && res.getStatus() == 200) {
                    String userJson = GsonUtil.object2Json(res.getData());
                    User user = new Gson().fromJson(userJson, User.class);
                    try {
                        setUserInfo(user);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtil.display(getActivity(), "加载用户信息失败-_--_-");
                }
            }

            @Override
            public void onFailure(Call<ResponseResult> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    //界面加载时初始化用户信息，其中用户图片加载会稍慢，所以放在最后面
    private void setUserInfo(User user) throws IOException {

        et_username.setText(user.getUserName());
        this.user = user;
        System.out.println("iconPath:-->"+user.getIconPath());
        if (user.getIconPath() != null) {
            //创建一个新线程，用于从网络上获取图片
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //从网络上获取图片
                    Bitmap bitmap = PhotoUtil.getPicture(user.getIconPath());

                    try {
                        Thread.sleep(2000);//线程休眠两秒钟
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    final Animation alpha = AnimationUtils.loadAnimation(getActivity(), R.anim.anim_alpha);//获取透明度变化动画资源

                    alpha.setRepeatCount(0);//循环显示
                    //发送一个Runnable对象
                    iv_userIcon.post(new Runnable() {
                        @Override
                        public void run() {
//                            iv_userIcon.setImageBitmap(bitmap);//在ImageView中显示从网络上获取到的图片
                            iv_userIcon.setImageBitmap(bitmap);
                        }

                    });

                }
            }).start();//开启线程
        }
    }





    private void uploadImg2QiNiu() {

        Configuration config = new Configuration.Builder()
                .useHttps(true)               // 是否使用https上传域名
                .zone(FixedZone.zone2)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        UploadManager uploadManager = new UploadManager();
        // 设置图片名字
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String key = "icon_" + sdf.format(new Date());
        String token = TokenUtil.userToken;
        System.out.println("token:-->" + token);


        Log.i(TAG, "picPath: " + filePath);
        System.out.println("filePathOut:"+filePath);
        //Auth.create(AccessKey, SecretKey).uploadToken("zhongshan-avatar")，这句就是生成token
        uploadManager.put(filePath, key, token, new UpCompletionHandler() {


            @Override
            public void complete(String key, ResponseInfo info, JSONObject res) {
                // info.error中包含了错误信息，可打印调试
                // 上传成功后将key值上传到自己的服务器
                System.out.println("开始上传\ninfo's"+info+"key:"+key);
                if (info.isOK()) {
                    System.out.println("token===" + token);
                    String headpicPath = "http://qv8hg5jct.hn-bkt.clouddn.com/" + key;
                    System.out.println( "complete: " + headpicPath);
                }
                //     uploadpictoQianMo(headpicPath, picPath);
            }
        }, null);


    }

    private void test(){
        System.out.println("<--进来了");
        Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent,REQUEST_CODE);
        System.out.println("出来了-->");

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode,  Intent data) {
        if (requestCode == 0x1 && resultCode == RESULT_OK) {
            if (data != null) {

                ContentResolver resolver = getActivity().getContentResolver();
                try {
                    // 获取圖片URI
                    Uri uri = data.getData();
                    // 将URI转换为路径：
                    String[] proj = { MediaStore.Images.Media.DATA };
                    Cursor cursor = getActivity().managedQuery(uri, proj, null, null, null);
                    //  这个是获得用户选择的图片的索引值
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    // 最后根据索引值获取图片路径
                    filePath = cursor.getString(column_index);

                    // 压缩成800*480
                    Bitmap bitmap = BitmapFactory.decodeFile(filePath);
                    // 设置imageview显示图片
                    iv_userIcon.setImageBitmap(bitmap);
                    // 设置textview显示路径
                    Log.i("aaa","photoPath"+filePath);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    /*
     * 剪切图片
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, 3);
    }


    //fragment刚加载时，从后台获取本用户信息
    @Override
    public void onStart() {
        super.onStart();
        System.out.println("个人界面初始化-->");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        initUserInfo();
    }
}